package com.zhuangfei.hpuhelper.view;

import com.hpu.bean.Info;
import com.hpu.callback.EncryptCallBack;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.InfoParser;
import com.hpu.service.EncryptService;
import com.hpu.service.InfoService;
import com.hpu.service.LoginService;
import com.hpu.tools.InputMethodTools;
import com.hpu.tools.ShareTools;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhuangfei.generalpage.BaseActivity;
import com.zhuangfei.hpuhelper.tools.ActivityTools;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.hpuhelper.tools.ReflectTools;
import com.zhuangfei.hpuhelper.tools.UrlConstantsTools;
import com.zhuangfei.hpuhelper.tools.VersionTools;
import com.zhuangfei.smartalert.core.LoadAlert;
import com.zhuangfei.smartalert.core.MessageAlert;
import com.zhuangfei.toolkit.IntentToolkit;
import com.zhuangfei.toolkit.tools.ToastTools;

import cn.lzf.serviceplatform.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewStub;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 登录页面
 * 
 * @author Administrator 刘壮飞
 * 
 */
public class LoadActivity extends BaseActivity implements OnClickListener {

	// 学号、密码、教务处密码
	String number, pw, jwpw, enctrypt;
		
	// 三个输入框 学号、vpn密码、教务处密码
	private EditText numberEditText;
	private EditText pwEditText;
	private EditText jwpwEditText;

	// 登录按钮
	private LinearLayout buttonLayout;

	// 隐藏的webview用来调用js加密
	private WebView webView;

	// 业务对象
	LoginService loginService;
	EncryptService encryptService;
	MessageAlert messageAlert;

	TextView protectTextView;
	TextView activeTextView;
	TextView failTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		long time=System.currentTimeMillis();
		setContentView(R.layout.activity_load2);
		ActivityTools.setTransparent(this);
		checkLogin();
	}

	public void bug(){
		String str=null;
		ToastTools.show(this,"这里有BUG");
		Log.i("Str",str.length()+"");
	}
    
	/**
	 * 判断是否登录，登录就跳转主页，否则显示登录页面
	 */
	private void checkLogin() {
		int login = (int) ShareTools.get(this, "login", 0);
		if (login == 1) {
			ActivityTools.toActivity(LoadActivity.this, MainActivity.class);
			finish();
		}else{
			initView();
			initEvent();
		}
	}

	/**
	 * 初始化View
	 */
	private void initView() {
		getViewHelper().showSuccessView();
		messageAlert=new MessageAlert(this);
		
		// 初始化业务类
		loginService = new LoginService(this,handler);
		encryptService = new EncryptService();

		// 初始化学号输入框、vpn密码、教务处密码
		numberEditText = (EditText) findViewById(R.id.id_load_number);
		pwEditText = (EditText) findViewById(R.id.id_load_pw);
		jwpwEditText = (EditText) findViewById(R.id.id_load_jwpw);
		
		
		// 登录按钮
		buttonLayout = (LinearLayout) findViewById(R.id.id_load_buttonlayout);
		
		// webview用来调用js来加密
		webView = (WebView) findViewById(R.id.id_load_webview);

		protectTextView=findViewById(R.id.id_load_protect);
		failTextView=findViewById(R.id.id_load_fail);
		activeTextView=findViewById(R.id.id_load_active);
	}

	/**
	 * 初始化事件
	 */
	private void initEvent() {
		buttonLayout.setOnClickListener(this);
		protectTextView.setOnClickListener(this);
		failTextView.setOnClickListener(this);
		activeTextView.setOnClickListener(this);
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new DefaultHandler(this) {
		@Override
		public void handleMessage(Message msg) {
			getViewHelper().showSuccessView();
			super.handleMessage(msg);
			switch (msg.what) {
			// 登录成功
			case HttpConstants.LOGIN_SUCCESS:
				getViewHelper().showEmptyView("登录成功，正在跳转..");
				saveLoginInfo(msg.obj.toString());
//				infoService.getInfo();
				ActivityTools.toActivity(LoadActivity.this, MainActivity.class);
				finish();
				break;

			default:
				break;
			}
		};
	};
	
	protected void saveLoginInfo(String cookie) {
		ShareTools.put(LoadActivity.this, "login", 1);
		ShareTools.put(LoadActivity.this,ShareConstants.STORE_LOGINCOOKIE, cookie);
		ShareTools.put(LoadActivity.this, ShareConstants.STORE_USER, number);
		ShareTools.put(LoadActivity.this, ShareConstants.STORE_IDCARD, pw);
		ShareTools.put(LoadActivity.this, ShareConstants.STORE_PASSWORD1, enctrypt);
		ShareTools.put(LoadActivity.this, ShareConstants.STORE_PASSWORD2, jwpw);

		CrashReport.setUserId(number);

	}

	/**
	 * 检查输入数据是否合法
	 * 
	 * @return
	 */
	public boolean checkInput() {
		number = numberEditText.getText().toString().trim();
		jwpw = jwpwEditText.getText().toString().trim();
		pw = pwEditText.getText().toString().trim();

		if (number.length() == 0 || jwpw.length() == 0 || pw.length() == 0)
			return false;
		return true;
	}

	/**
	 * 保存用户信息
	 *
	 */
	public void saveInfo(Info info) {
		if (info==null) return;
		System.out.println(info.getName());
		ShareTools.put(this,ShareConstants.STORE_USER_MAJOR, info.getMajor());
		ShareTools.put(this, ShareConstants.STORE_USER_INSTITUTE, info.getInstitute());
		ShareTools.put(this, ShareConstants.STORE_USER_TESTNUMBER, info.getTestNumber());
		ShareTools.put(this, ShareConstants.STORE_USER_CLASS, info.getClasses());
		ShareTools.put(this, ShareConstants.STORE_USER_SEX, info.getSex());
		ShareTools.put(this, ShareConstants.STORE_USER_NAME, info.getName());
	}
	
	/**
	 * 登录
	 */
	private void doLogin() {
		if (checkInput()) {
			InputMethodTools.close(LoadActivity.this);
			getViewHelper().showEmptyView("正在登录..");
			encryptService.doEncrypt(webView, pw, new EncryptCallBack() {

				@Override
				public void onFinish(String result) {
					enctrypt = result;
					loginService.login(number, result, jwpw);
				}
			});
		} else
			Toast.makeText(LoadActivity.this, "信息不全,请补充完整", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.id_load_buttonlayout:
			doLogin();
			break;

			case R.id.id_load_protect:
				new IntentToolkit().with(LoadActivity.this)
						.target(WebViewActivity.class)
						.put("title","用户隐私协议")
						.put("url", UrlConstantsTools.URL_PROTECT)
						.execute();
				break;

			case R.id.id_load_fail:
				showNormalDialog();
				break;

			case R.id.id_load_active:
				new IntentToolkit().with(LoadActivity.this)
						.target(WebViewActivity.class)
						.put("title","账号激活")
						.put("url", ReflectTools.URL_ACTIVE)
						.execute();
				break;
		default:
			break;
		}
	}

	private void showNormalDialog() {
		AlertDialog.Builder normalDialog =
				new AlertDialog.Builder(LoadActivity.this);
		AlertDialog dialog = normalDialog.create();
		normalDialog.setTitle("疑问解答");
		normalDialog.setMessage("1.账号为学号;教务处密码为登录教务处的密码,默认为学号;校园网密码为登录校园WIFI的密码，默认为身份证后六位，X大写\n\n" +
				"2.2015届的校园网账号默认时开通的，2016、2017届..的应该先激活校园网账号\n\n" +
				"3.本系统可以在校外（外网）环境下访问校内的各种服务\n\n4.因学校服务器限制，一个时间段内大量流量涌入会导致登录失败，错误提示可能会不太准确\n\n" +
				"4.激活账号的按钮有时不可用，南校区2号实验楼2604可以进行账号激活以及密码修改\n\n" +
				"4.，如有意见或问题，请加群：617094684，技术人员会快速跟进\n\n" +
				"5.如需商务合作，请发邮件至1193600556@qq.com");
		normalDialog.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});

		normalDialog.create().show();
	}
	
	@Override
	public void onBackPressed() {
		ActivityTools.toHome(this);
	}
}
